import React, { Component } from 'react'
import { Card, Form, Button, Input, InputNumber, Cascader, Upload, Modal, message } from 'antd';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons'
import {reqGetCategoryList,reqAddProduct,reqDeletePic} from '../../../api/index'
import PicturesWall from '../../../component/imgupload/imgupload'

import './all.less'

const Item = Form.Item

export default class AddUpdate extends Component {

    state = {
        /* 
        |参数		       |是否必选 |类型     |说明
|categoryId    |Y       |string   |分类ID
|pCategoryId   |Y       |string   |父分类ID
|name          |Y       |string   |商品名称
|desc          |N       |string   |商品描述
|price         |N       |string   |商品价格
|detail        |N       |string   |商品详情
|imgs          |N       |array   |商品图片名数组 */
        PcategoryList:[],//父分类的集合
//
        categoryId: '',//级联选择的分类id
        pCategoryId: '',//父分类id
        name:'',
        desc:'',
        price:0,
        detail:'',
        imgs:[],
        _id:'',
        isUpdate:false,//表示更新商品还是添加新的商品
    }

    onFinish = async(values) => {
        console.log("提交表单成功",values)
        console.log(this.state)
        values.categoryId = values.productClass[1]
        values.pCategoryId = values.productClass[0]
        values.imgs = this.state.imgs
        const {categoryId,pCategoryId ,name,desc,price,detail,imgs} = values
        console.log("--------------------------------------------")
        console.log(categoryId,pCategoryId ,name,desc,price,detail,imgs)
        //将图片数据保存保存下来，如果用户在销毁窗口之前没有提交，服务器自动删除图片
        let result = await reqAddProduct({categoryId,pCategoryId ,name,desc,price,detail,imgs})
        if(result.data.status===0){
            message.success("添加成功")
              //提交数据之后将本地数据清除
            this.setState({imgs:[]})
        }else{
            message.error("添加失败")
        }
    }
    getImages  = (imgs)=>{
        this.setState({imgs})
    }
//级联菜单选择完毕的回调函数
    onChange = (value, selectedOptions) => {
        //判断是在一级目录下创建还是在二级目录下创建
        if(value.length===1){
            //在一级目录下创建
            this.setState({pCategoryId:value[0],categoryId:''})
        }else{
            //在二级目录下创建，默认
            this.setState({pCategoryId:value[0],categoryId:value[1]})
            console.log("选择完成！！！")
        }
    }
    //选中每一条以及菜单项，加载其二级分类
    loadData =async (selectedOptions)=>{
        console.log("这个个什么东西",selectedOptions)
        let id = selectedOptions[0].value
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        //发送请求获取数据
        let {data} = await reqGetCategoryList(id)
        //同样对数据进行过滤
        targetOption.children = data.data.map((item)=>{
            return{ label:item.name,value:item._id}
        })
        targetOption.loading = false;
    }

   componentWillMount(){
       //这样做可以解决undefine的问题，页面运行bug
       let {item} = this.props.location.state
       if(item){
           this.setState({isUpdate:true})
       }
       this.item = item || {}
   }
    async componentDidMount(){
        //初始化获取所有以及分类的列表，作为级联选择的第一级
        let {data} = await reqGetCategoryList(0)
        //将名字和_id进行筛选
        let PcategoryList = data.data.map((item)=>{
            return {value:item._id,label:item.name, isLeaf: false,}
        })
        this.setState({PcategoryList})
    }
    //在销毁页面之前还没有提交数据，就删除已经添加的图片
    componentWillUnmount(){
        let {imgs} = this.state
        if(imgs.length!=0){
            //发送请求去销毁图片
            for(let i=0;i<imgs.length;i++){
                let result = reqDeletePic(imgs[i])
            }
        }
    }
    render() {
        const { title } = this.props.location.state
        
        const titleNode = (
            <span>
                <ArrowLeftOutlined style={{ fontSize: '20px' }} onClick={() => this.props.history.goBack()} />
                <span style={{ color: 'green', fontSize: '20px', marginLeft: '30px' }}>{title}</span>
            </span>
        )
        const layout = {
            labelCol: { span: 2 },
            wrapperCol: { span: 6 },
        };
        return (
            <Card title={titleNode} >
                <Form
                    {...layout}
                    name="basic"
                    initialValues={{ remember: true }}
                    onFinish={this.onFinish}
                >
                    <Form.Item
                        label="商品名称"
                        initialValue={this.item.name}
                        name="name"
                        rules={[{ required: true, message: '请输入商品名称' }]}
                    >
                        <Input  placeholder='请输入商品名称' />
                    </Form.Item>

                    <Form.Item
                        label="商品描述"
                        name="desc"
                        initialValue={this.item.desc}
                        rules={[{ required: true, message: '请输入商品描述' }]}
                    >
                        <Input placeholder='请输入商品描述' />
                    </Form.Item>
                    <Form.Item
                        label="商品价格(元)"
                        name="price"
                        initialValue={this.item.price}
                        rules={[{ required: true, message: '请选择商品价格' }]}
                        style={{ display: 'flex' }}
                    >
                        <InputNumber style={{ width: 316 }}
                            min={1} onChange={this.onChange} placeholder='请输入商品价格' />
                    </Form.Item>
                    <Form.Item
                        label="商品分类"
                        name="productClass"
                        rules={[{ required: true, message: '请选择商品分类' }]}
                    >
                        <Cascader
                            options={this.state.PcategoryList}
                            expandTrigger="hover"
                            onChange={this.onChange}
                            loadData = {this.loadData}
                            onPopupVisibleChange = {this.onPopupVisibleChange}
                            notFoundContent="这一项什么也没有"
                            placeholder="请选择商品分类"
                        />
                    </Form.Item>
                    <Form.Item
                        label="商品图片"
                        name="imgs"
                    >
                    <PicturesWall getImages = {this.getImages} imgs = {this.item.imgs}></PicturesWall> 
                    </Form.Item>

                    <Form.Item
                        label="商品详情"
                        name="detail"
                        initialValue={this.item.detail}
                        rules={[{ required: true, message: '请选择商品详情' }]}
                    >
                        <Input placeholder='请选择商品详情' />
                    </Form.Item>


                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                            Submit
        </Button>
                    </Form.Item>
                </Form>
            </Card>
        )
    }
}